#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
#TODO: documentation!
"""

__version__ = '$Id$'


from pyglet import gl
from bipy import view
from bipy import entity

class Scene(object):

    def __init__(self, engine):
        # Save reference to Bipy engine
        self.engine = engine
        # Create some views
        v = view.View(self, screen_pos=(30,30), screen_size=(300, 300))
        v2 = view.View(self, screen_pos=(400,200), screen_size=(200,200))
        # Push but /don't/ Pop a list of views
        # Engine Pops all of this scene's views when this scene is popped.
        # So each scene manages their own scenes for the life of the scene
        # Then the engine cleans up :)
        engine.view_manager.push_views( [v, v2] )
        # Create some entities   
        self.entities = []
        for i in xrange(100):
            self.entities.append(entity.Entity())
            
    def draw_entities(self):
        for entity in self.entities:
                entity.draw()
                
    def draw_axis(self):
        gl.glPushMatrix()
        # Draw axis reference
        gl.glLineWidth(3.0)
        gl.glBegin(gl.GL_LINES)
        gl.glColor3f(1.0, 0.0, 0.0)
        gl.glVertex3f(-100.0, 0.0, 0.0)
        gl.glVertex3f(100.0, 0.0, 0.0)
        
        gl.glColor3f(0.0, 1.0, 0.0)
        gl.glVertex3f(0.0, -100.0, 0.0)
        gl.glVertex3f(0.0, 100.0, 0.0)
        
        gl.glColor3f(0.0, 0.0, 1.0)
        gl.glVertex3f(0.0, 0.0, -100.0)
        gl.glVertex3f(0.0, 0.0, 100.0)
        gl.glEnd()
        gl.glPopMatrix()
        
    def on_draw(self):
        # Handle the 'on_draw' event
        # This is invoked under the context ofthe viewports (GL_MODELVIEW)
        # maintained by the scene.
        # TODO: draw all entities that are visible to the camera
        # Clear buffer
        self.engine.clear()
        vm = self.engine.view_manager
        # Render all current views
        gl.glPushMatrix()
        views = vm.get_views()
        if views:
            for view in views:
                view.set_viewport()
                self.draw_entities()
                self.draw_axis()
                #self.dispatch_event('on_draw')
        # Render FPS counter
        gl.glPopMatrix()
        self.engine.fps_display.draw()
        self.engine.flip()